import React, { useState, useRef } from 'react';

export default function CountHook() {

  const [ count, setCount ] = useState(0);
  const selectRef = useRef();

  // useEffect(() => {
  //   let timer = setInterval(() => {
  //     setCount(count => count + 1);
  //   }, 1000);

  //   return () => {
  //     clearInterval(timer);
  //   } 
  // }, [])

  function handleAdd() {
    const { value } = selectRef.current;

    /**
     * setCount 
     * 写法一：setCount(count + value * 1);
     * 写法二：setCount(count => count + value * 1);
     * 
     */ 
    
    setCount(count => count + value * 1);
  }

  function handleAsyncAdd() {
    const { value } = selectRef.current;

    setTimeout(() => {
      setCount(count => count + value * 1);
    }, 1000);
  }

  return (
    <div>
      <h1>组件CountHook</h1>
      <h4>count值：{ count }</h4>
      <select ref={ selectRef } placeholder="请选择">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button onClick={ handleAdd }>同步+加</button>
      <button onClick={ handleAsyncAdd }>异步+加</button>
    </div>
  )
}

